import 'dart:core';

import 'package:flutter/material.dart';
import 'package:xindong/common/xindong_api_path.dart';
import 'package:xindong/common/xindong_app_info.dart';
import 'package:xindong/common/xindong_sezhi.dart';
import 'package:xindong/common/xindong_methods.dart';
import 'package:xindong/manager/network/xindong_networking.dart';
import 'package:xindong/routes/call/controller/xindong_call_controller.dart';
import 'package:xindong/utils/xindong_conversion_util.dart';
import 'package:xindong/widgets/dialog/xindong_base_alert.dart';
import 'package:xindong/widgets/dialog/version/xindong_version_action_view.dart';

// 版本
class XinDongVersionDialog extends StatelessWidget {
  final String url;
  final String version;
  final String content;
  final bool force;

  const XinDongVersionDialog(
      {super.key, required this.url, required this.version, required this.content, required this.force});

  // 检测 - 要在AppInfo获取之后
  static checkNeedUpgrade() async {
    final version = XinDongAppDeviceInfo.instance.packageInfo?.version;
    if (version == null) {
      return;
    }

    try {
      final response = await XinDongNetworking.instance.request(
        XinDongApi.userMemberConfig,
        method: XinDongHttpMethod.post,
        addUserId: false,
      );
      if (response.code == XinDongServerStatus.success) {
        // 存在版本数据
        if (response.data.containsKey("anzhuourl") && response.data.containsKey("anzhuonum")) {
          final serverUrl = "${response.data["anzhuourl"]}";
          final serverVersion = "${response.data["anzhuonum"]}";
          final versionNote = "${response.data["version_note"]}";
          final force = "${response.data["adsw"]}" == "1";
          XinDongCallController.to.timer_switch = response.data["timer_switch"];
          // Android和iOS比较版本大小
          bool had = XinDongConversionUtil.hasNewVersion(version, serverVersion);
          if (had) {
            // 有新版本
            return XinDongVersionDialog._show(serverUrl, serverVersion, versionNote, force);
          } else {
            // 只有安卓需要再判断build版本
            // if (Platform.isAndroid && int.parse(banbenCode) < (model.versioncode ?? 0)) {
            //   // 有新版本
            //   return XinDongVersionDialog._show(model);
            // }
          }
        }
      } else {
        // 只在新版本时提示一次，已经提示过的会在上面return了
        Future.delayed(const Duration(minutes: 5)).whenComplete(() => checkNeedUpgrade());
      }
    } catch (error) {
      mCatchPrint(error);
    }
  }

  // 队列显示提示框
  static _show(String url, String version, String content, bool force) {
    return showSmartAlert(
      alert: XinDongVersionDialog(url: url, version: version, content: content, force: force),
      hideWhenTouchOutside: force == false,
    );
  }

  @override
  Widget build(BuildContext context) {
    return XinDongBaseDialog(
      hideWhenTouchOutside: force == false,
      body: Column(
        mainAxisSize: MainAxisSize.min,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Container(
            width: 290,
            decoration: BoxDecoration(
              color: DZColors.dialog,
              borderRadius: BorderRadius.circular(16.0),
            ),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                const SizedBox(height: 20),
                const Text(
                  "发现新版本",
                  style: TextStyle(color: DZColors.titleColor, fontSize: 24),
                ),
                const SizedBox(height: 10),
                Container(
                  padding: const EdgeInsets.fromLTRB(10, 5, 10, 5),
                  decoration: BoxDecoration(borderRadius: BorderRadius.circular(20), color: DZColors.appBar),
                  child: Text(
                    "最新：v$version",
                    style: const TextStyle(color: DZColors.contentColor, fontSize: 15, height: 1.2),
                  ),
                ),

                // 更新内容
                Container(
                  padding: const EdgeInsets.only(top: 10, left: 25, right: 20),
                  alignment: Alignment.centerLeft,
                  child: Text(
                    content,
                    style: const TextStyle(fontSize: 15, fontWeight: FontWeight.normal, color: DZColors.contentColor),
                    strutStyle: const StrutStyle(forceStrutHeight: true, height: 1, leading: 1),
                  ),
                ),

                // 立即升级
                XinDongVersionActionView(url: url, version: version, force: force),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
